<?php
include_once("../includes/common.php");
include_once("../class/User.class.php");
include_once("../class/Action.class.php");
include_once("../class/Comments.class.php");
require_once("../islogin.php");

if ($islogin!=1){
    header('Location: /login.php');
    exit;
}

$menuavatar = !$user_info["message"]["avatar"] ? "/data/avatar/default.jpg" : $user_info["message"]["avatar"];

$setVparam = $_GET['type'] ?? '';
$allowedValues = [
    'view_history' => [
        'title' => $user_info["message"]["nickname"] . ' 浏览记录',
        'view' => 1
    ],
    'so_history' => [
        'title' => $user_info["message"]["nickname"] . ' 搜索记录',
        'view' => 2
    ],
    'comments_history' => [
        'title' => $user_info["message"]["nickname"] . ' 评论记录',
        'view' => 3
    ],
    'all_comments' => [
        'title' => '评论详情',
        'view' => 4
    ],
];

if (array_key_exists($setVparam, $allowedValues)) {
    $pageName = $allowedValues[$setVparam]['title']; // 根据 $get 设置标题
    $history_type = $allowedValues[$setVparam]['view']; // 获取对应的 view 值
}

if($history_type==4){
    $ulist_type = 10;
    $history_type = null;
}

if(!$pageName){
    exit('error pagename');
}

//初始化类处
$action = new Action();
$comment = new Comments();


//构造page
$nowPage = $_GET['page'] ?? 1;
if($nowPage<0){
    exit('page error');
}
$pageNum = 12;
$totalPage = 0;

// 获取当前 URL
$currentUrl = $_SERVER['REQUEST_URI'];
// 解析当前 URL
$parsedUrl = parse_url($currentUrl);
$queryParams = [];
if (isset($parsedUrl['query'])) {
    parse_str($parsedUrl['query'], $queryParams);
}

// 判断 $nowPage 是否为整数
if (!filter_var($nowPage, FILTER_VALIDATE_INT)||$nowPage==0) {
    exit(); // 如果不是整数，退出并显示消息
}
//浏览记录页面
if ($history_type==1){
    $history_info = json_decode($action->getUserViewHistory($user_info['message']['user_id'],$nowPage,$pageNum),true);
    $totalPage = $action->getViewHisTotalPages($user_info['message']['user_id'],$pageNum);
    $apiType = 'hideview';
}
if ($history_type==2){
    $history_info = json_decode($action->getUserSearchHistory($user_info['message']['user_id'],$nowPage,$pageNum),true);
    $totalPage = $action->getSearchHisTotalPages($user_info['message']['user_id'],$pageNum);
    $apiType = 'hideso';
}
if ($history_type==3){
    $history_info = json_decode($comment->getUserComments($user_info['message']['user_id'],$nowPage,$pageNum),true);
    //var_dump($history_info);
    $totalPage = $comment->getUCommentsTotalPage($user_info['message']['user_id'],$pageNum);
    $apiType = 'udelpl';
}
if ($ulist_type==10){
    $history_info = json_decode($comment->getNotifyComments($user_info['message']['user_id'],$nowPage,$pageNum),true);
    $totalPage = $comment->getNotifyCommentsTotal($user_info['message']['user_id'],$pageNum);
    $apiType = 'delotherpl';
}


if($_GET['so']){
    $totalPage = 1;
    $pageNum = 1000;
    $searchKeyword = $_GET['so'] ?? ''; // 获取搜索关键词

    if($history_type==1){
        $sodataArray = json_decode($action->getUserViewHistory($user_info['message']['user_id'],1,1000),true);
        $filteredResults = array_filter($sodataArray, function($item) use ($searchKeyword) {
            return stripos($item['title'], $searchKeyword) !== false; // 不区分大小写的模糊匹配
        });
    }elseif ($history_type==2){
        $sodataArray = json_decode($action->getUserSearchHistory($user_info['message']['user_id'],1,1000),true);
        $filteredResults = array_filter($sodataArray, function($item) use ($searchKeyword) {
            return stripos($item['search_keywords'], $searchKeyword) !== false; // 不区分大小写的模糊匹配
        });
    }elseif ($history_type==3){
        $sodataArray = json_decode($comment->getUserComments($user_info['message']['user_id'],1,1000),true);
        $filteredResults = array_filter($sodataArray, function($item) use ($searchKeyword) {
            return stripos($item['content'], $searchKeyword) !== false || stripos($item['title'], $searchKeyword) !== false; // 对 评论内容 和 笔记标题 进行模糊匹配
        });
    }elseif ($ulist_type==10){
        $sodataArray = json_decode($comment->getNotifyComments($user_info['message']['user_id'],1,1000),true);
        $filteredResults = array_filter($sodataArray, function($item) use ($searchKeyword) {
            return stripos($item['content'], $searchKeyword) !== false || stripos($item['title'], $searchKeyword) !== false; // 对 评论内容 和 笔记标题 进行模糊匹配
        });
    }
    $filteredResults = array_values($filteredResults);  //编制索引

    if($history_info){
        $history_info = $filteredResults;
    }
}

// 构建链接 - 必须放最后得等上面查好总页数
$nextPage = $nowPage + 1 > $totalPage ? $totalPage : $nowPage + 1;
$prevPage = $nowPage - 1 < 1 ? 1 : $nowPage - 1;
// 更新 page 参数
$queryParams['page'] = $nextPage; // 对于下一页
$nextPageLink = $parsedUrl['path'] . '?' . http_build_query($queryParams);

// 更新 page 参数
$queryParams['page'] = $prevPage; // 对于上一页
$prevPageLink = $parsedUrl['path'] . '?' . http_build_query($queryParams);

if(!$history_info){
    $history_info = [];
}

?>
<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <?php require_once('head.php'); ?>
    <link rel="stylesheet" href="/static/css/message.css">
</head> 
<body>
    
<!--==================== Preloader Start ====================-->
  <div class="preloader">
    <div class="loader"></div>
  </div>
<!--==================== Preloader End ====================-->

<!--==================== Sidebar Overlay End ====================-->
<div class="side-overlay"></div>
<!--==================== Sidebar Overlay End ====================-->

<?php require_once('user_menu.php'); ?>

    <div class="dashboard-main-wrapper">
        <?php require_once('top_navbar.php'); ?>

        <div class="dashboard-body">

            <div class="row gy-4">
                <!-- Email List Start -->
                <div class="col-xl">
                    <div class="card h-100 p-0 email-card">
                        <div class="card-header border-bottom bg-base py-16 px-24">
                            <div class="d-flex flex-wrap align-items-center justify-content-between gap-4">
                                <div class="flex-center gap-16">
                                    <div class="form-check style-check flex-center mb-0 gap-8">
                                        <input class="form-check-input radius-4 border border-gray-200" type="checkbox" name="checkbox" id="selectAll">
                                    </div>
                                    <span class="text"><?php echo $pageName?></span>
                                    <button type="button" class="delete-button text-secondary-light text-xl d-flex  rounded-4">
                                        <i class="ph ph-trash"></i>
                                    </button>
                                    <?php if ($history_type!=3&&$ulist_type!=10){?>
                                        <button type="button" class="clearall-button text-secondary-light text-xl d-flex  rounded-4">
                                            <i class="ph ph-broom"></i>
                                        </button>
                                    <?php }?>
                                    <button type="button" class="reload-button text-secondary-light text-xl d-flex rounded-4">
                                        <i class="ph ph-arrows-clockwise"></i>
                                    </button>
                                </div>
                                <div class="flex-center gap-16">
                                    <span class="text-secondary-light line-height-1">1-<?php echo $totalPage?> 页 每页 <?php echo $pageNum?> 条</span>
                                    <nav aria-label="Page navigation example">
                                        <ul class="pagination">
                                            <li class="page-item">
                                                <a class="page-link d-flex border text-gray-500 hover-bg-gray-50 text-xl w-40 h-32 flex-center" href="<?php echo $prevPageLink; ?>"><i class="ph ph-caret-left"></i> </a>
                                            </li>
                                            <li class="page-item">
                                                <a class="page-link d-flex border text-gray-500 hover-bg-gray-50 text-xl w-40 h-32 flex-center" href="<?php echo $nextPageLink; ?>"><i class="ph ph-caret-right"></i> </a>
                                            </li>
                                        </ul>
                                    </nav>
                                </div>
                            </div>
                        </div>
                        <div class="card-body p-0">
                            <ul class="overflow-x-auto scroll-sm scroll-sm-horizontal">
                                <!--list-->
                                <?php if ($history_type==1){?>
                                    <?php for ($i = 0; $i < count($history_info); $i++) { ?>
                                        <li data-nid="<?php echo $history_info[$i]['note_id']; ?>" class="email-item px-24 py-16 flex-align gap-16 border-bottom border-gray-100 cursor-pointer min-w-max-content">
                                            <div class="form-check style-check flex-center mb-0 gap-8">
                                                <input class="form-check-input radius-4 border border-gray-200" type="checkbox" name="checkbox">
                                            </div>
                                            <a href="/explore.php?id=<?php echo $history_info[$i]['note_id']; ?>" class="text-heading fw-medium text-md text-line-1">《<?php echo $history_info[$i]['title']; ?>》</a>
                                            <a href="/explore.php?id=<?php echo $history_info[$i]['note_id']; ?>" class="text-heading fw-medium mb-0 text-line-1 max-w-740"><?php echo $history_info[$i]['content']; ?></a>
                                            <span class="text-heading fw-medium min-w-max-content ms-auto"><?php echo formatTimestampToDate($history_info[$i]['action_time']); ?></span>
                                        </li>
                                    <?php } ?>
                                <?php }elseif ($history_type==2){?>
                                    <?php for ($i = 0; $i < count($history_info); $i++) { ?>
                                        <li data-nid="<?php echo $history_info[$i]['id']; ?>" class="email-item px-24 py-16 flex-align gap-16 border-bottom border-gray-100 cursor-pointer min-w-max-content">
                                            <div class="form-check style-check flex-center mb-0 gap-8">
                                                <input class="form-check-input radius-4 border border-gray-200" type="checkbox" name="checkbox">
                                            </div>
                                            <a href="/?so=<?php echo $history_info[$i]['search_keywords']; ?>" class="text-heading fw-medium text-md text-line-1"><?php echo $history_info[$i]['search_keywords']; ?></a>
                                            <span class="text-heading fw-medium min-w-max-content ms-auto"><?php echo formatTimestampToDate($history_info[$i]['action_time']); ?></span>
                                        </li>
                                    <?php } ?>

                                <?php }elseif ($history_type==3||$ulist_type==10){?>
                                <?php for ($i = 0; $i < count($history_info); $i++) { ?>
                                <li data-nid="<?php echo $history_info[$i]['comments_id']; ?>" class="email-item px-24 py-16 flex-align gap-16 border-bottom border-gray-100 cursor-pointer min-w-max-content">
                                    <div class="form-check style-check flex-center mb-0 gap-8">
                                        <input class="form-check-input radius-4 border border-gray-200" type="checkbox" name="checkbox">
                                    </div>
                                    <a href="/explore.php?id=<?php echo $history_info[$i]['note_id']; ?>" class="text-heading fw-medium mb-0 text-line-1 max-w-740"><?php echo $history_info[$i]['nickname']; ?> 在笔记《<?php echo $history_info[$i]['title']; ?>》发表了评论：<?php echo $history_info[$i]['content']; ?></a>
                                    <a href="/explore.php?id=<?php echo $history_info[$i]['note_id']; ?>" class="text-heading fw-medium text-md text-line-1"></a>
                                    <a href="/explore.php?id=<?php echo $history_info[$i]['note_id']; ?>" class="text-heading fw-medium text-md text-line-1"></a>
                                    <span class="text-heading fw-medium min-w-max-content ms-auto">评论时间：<?php echo formatTimestampToDate($history_info[$i]['comments_time']); ?> 发布地区：<?php echo getIpProvince($history_info[$i]['publish_ip']); ?> </span>
                                </li>
                                <?php } ?>

                                <?php }?>



                            </ul>
                        </div>
                    </div>
                </div>
                <!-- Email List End -->

            </div>
            
        </div>

        <?php require_once('footer.php'); ?>
    </div>


<?php require_once('foot.php'); ?>
<!-- main js -->
<script src="/static/js/message.min.js"></script>

<script>
    let uid = '<?php echo $user_info['message']['user_id'];?>';
    let apiType = '<?php echo $apiType;?>';
    // Table Header Checkbox checked all js Start
    $('#selectAll').on('change', function () {
        $('.form-check .form-check-input').prop('checked', $(this).prop('checked')); 
        
        if ($(this).prop('checked')) {
            $('.email-item').addClass('active');
        } else {
            $('.email-item').removeClass('active');
        }
    }); 

    // Active Item with js
    $('.form-check .form-check-input').on('change', function () {
        if ($(this).is(':checked')) {
            $(this).closest('.email-item').addClass('active'); 
        } else {
            $(this).closest('.email-item').removeClass('active'); 
        }
    });

    // Selected Checkbox count amount js End
    //删除jq
    $('.delete-button').on('click', function () {

        let hasActive = false;

        $('.email-item').each(function() {
            if ($(this).hasClass('active')) {
                hasActive = true;
            }
        });

        if (!hasActive) {
            Qmsg.info('没有选中的记录');
        }


        $('.email-item.active').addClass('d-none');
        $('.email-item.active').each(function() {
            var dataNid = $(this).data('nid'); // 获取当前元素的 data-nid 值
            Qmsg.success('删除成功！');
            $.ajax({
                <?php if($history_type==3||$ulist_type==10){?>
                url: '/api/comments.php?type='+apiType,
                <?php }else{?>
                url: '/api/action.php?type='+apiType,
                <?php }?>
                method: 'POST', // 请求方式
                data: {
                    uid: uid,
                    nid: dataNid,
                    id: dataNid,
                    cid: dataNid,
                },
                success: function(response) {
                    //console.log(response);
                },
                error: function(xhr, status, error) {
                    //console.log("Error: " + error);
                }
            });
        });
    });


    let clickCount = 0;
    let clickTimer;

    $('.clearall-button').on('click', function () {
        clickCount++; // 每次点击增加计数

        // 如果是第一次点击，启动1秒计时器
        if (clickCount === 1) {
            clickTimer = setTimeout(function () {
                clickCount = 0;
            }, 1000);
        }

        // 如果5秒内点击了3次，则执行内容
        if (clickCount === 3) {
            clearTimeout(clickTimer); // 清除计时器


            $('.email-item').addClass('d-none');
            Qmsg.success('清空成功');
            $.ajax({
                url: '/api/action.php?type='+apiType, // API 接口地址
                method: 'POST', // 请求方式
                data: {
                    uid: uid,
                    nid: '',
                    //id: '',
                },
                success: function(response) {
                    //console.log(response);

                },
                error: function(xhr, status, error) {
                    //console.log("Error: " + error);
                }
            });

            clickCount = 0; // 重置计数器
        }else{
            Qmsg.info('连点三次 <i class="ph ph-broom"></i> 会清空所有记录！该操作不可逆！',{
                html:true,
            })
            //Qmsg.info('连点三次按钮该会清空所有记录！该操作不可逆！');
        }
    });

   
    // Page Reload Js
    $(".reload-button").on("click", function() {
        history.go(0);
    });
   
    // Starred Button js
    $('.starred-button').on('click', function () {
        var icon = $(this).children('i');
        if(icon.hasClass('ph ph-star')) {
            icon.removeClass('ph ph-star'); 
            icon.addClass('ph-fill ph-star text-warning-600'); 
        } else {
            icon.removeClass('ph-fill ph-star text-warning-600'); 
            icon.addClass('ph ph-star'); 
        }
    }); 
</script>


    </body>
</html>